package com.mytrip.webapp.interceptor;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import com.mytrip.base.exception.BaseException;
import com.mytrip.util.Constant;
import com.mytrip.util.CookieWrapper;
import com.mytrip.webapp.exception.ActionExceptionWraper;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class CookieInterceptor extends AbstractInterceptor{
	
	private final Log log = LogFactory.getLog(CookieInterceptor.class);

	private static final long serialVersionUID = 8917804769342032945L;

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		try{
			HttpServletRequest request = (HttpServletRequest) invocation.getInvocationContext().get(ServletActionContext.HTTP_REQUEST);
			HttpServletResponse response = (HttpServletResponse) invocation.getInvocationContext().get(ServletActionContext.HTTP_RESPONSE);
			
			CookieWrapper cookieWrapper = new CookieWrapper(request, response);
			Cookie cookie = cookieWrapper.getCookie("commonLoginCookie");
			if (cookie == null) {
				return "backendLogin";
			} else {
				int split = cookie.getValue().lastIndexOf("-_-");
				String d = cookie.getValue().substring(split + 3);
				if (isCookieExpire(d, Constant.COOKIE_EXPIRE_MINUTES)) {
					cookieWrapper.clearCookie("commonLoginCookie", ".mytrip.com");
					return "backendLogin";
				}
				
				SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				
				cookieWrapper.setCookie("commonLoginCookie", cookie.getValue().substring(0, split + 3) + sf.format(new Date()), ".mytrip.com");
			}
			return invocation.invoke();
		} catch (BaseException e){
			ActionExceptionWraper aw = new ActionExceptionWraper();
			aw.addActionError("[" + e.getErrCode() + "]:" + e.getMessage());
			
			invocation.getStack().push(aw);
			return "baseError";
		} catch (Exception e){
			log.error("::",e);
			ActionExceptionWraper aw = new ActionExceptionWraper();
			aw.addActionError("[unknow error]:" + e.getMessage().replaceAll("\n", "<br>"));
			
			invocation.getStack().push(aw);
			return "baseError";
		}
		
	}
	
	/**
	 * 判断COOKIE是否过期
	 * 
	 * @param strDate 上次访问的时间，格式：yyyy-MM-dd HH:mm:ss
	 * @param minutes 过期时间（以分为单位）
	 * @return true 过期 false 未过期
	 */
	private boolean isCookieExpire(String strDate, int minutes) {

		Calendar c = Calendar.getInstance();
		int year = Integer.parseInt(strDate.substring(0, 4));
		int month = Integer.parseInt(strDate.substring(5, 7)) - 1;
		int day = Integer.parseInt(strDate.substring(8, 10));
		int hour = Integer.parseInt(strDate.substring(11, 13));
		int minute = Integer.parseInt(strDate.substring(14, 16));
		int second = Integer.parseInt(strDate.substring(17));
		c.set(year, month, day, hour, minute, second);
		c.add(Calendar.MINUTE, minutes);
		return c.before(Calendar.getInstance());
	}
	
}
